<template>
    <el-tabs :tab-position="tabPosition" class="demo-tabs">
        <el-tab-pane label="个人信息">
            <div style="display: flex; align-items: center; justify-content: flex-start;">
                <div class="demo-type">
                    <el-avatar :size="60"  @error="errorHandler">
                      <img  :src="image" @click="openFileInput" />
                    </el-avatar>
                    <input ref="avatarInput" type="file" style="display: none" @change="handleAvatarChange">
                  </div>

                <div class="webname" style="margin-top: auto; margin-bottom: auto; margin-left: 10px;">{{ user.webname }}</div>
            </div>
            <el-descriptions title='个人信息'>
                <el-descriptions-item label="姓名：">{{ user.name }}</el-descriptions-item>
                <el-descriptions-item label="生日：">{{ user.birthday }}</el-descriptions-item>
                <el-descriptions-item label="电话：">{{ user.tel }}</el-descriptions-item>
                <el-descriptions-item label="账号：">{{ user.username }}</el-descriptions-item>
                <br>
                <el-descriptions-item label="年龄：">
                    <el-tag size="small"> {{ user.age }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="邮箱：">{{ user.email }}</el-descriptions-item>
                <el-descriptions-item label="居住地址：">{{ user.address }}</el-descriptions-item>
            </el-descriptions>
            <el-button plain @click="dialogTableVisible = true">
                修改信息
            </el-button>

            <el-dialog v-model="dialogTableVisible" title="信息修改" width="800">
                <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules"
                    label-width="auto" class="demo-ruleForm">
                    <el-form-item label="网名" prop="webname">
                        <el-input v-model="ruleForm.webname" />
                    </el-form-item>
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="ruleForm.name" />
                    </el-form-item>
                    <el-form-item label="电话号码" prop="tel">
                        <el-input v-model.number="ruleForm.tel" />
                    </el-form-item>
                    <el-form-item label="电子邮箱" prop="email">
                        <el-input v-model="ruleForm.email" />
                    </el-form-item>
                    <el-form-item label="居住地址：" prop="address">
                        <el-input v-model="ruleForm.address" />
                    </el-form-item>
                    <el-form-item label="出生日期" prop="birthday">
                        <el-date-picker v-model="ruleForm.birthday" type="date" placeholder="Pick a date" clearable />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm(ruleFormRef)">
                            提交
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </el-tab-pane>


        <el-tab-pane label="收藏">
            <div class="Topstory-content">
                <ul v-if="collect && collect.length > 0">
                    <li v-for="v in collect" :key="v.id" class="topic-item">
                        <div>
                            <div class="topstory-hd">
                                <span>{{ v.publisher_name }}</span>
                                <!-- 添加删除按钮 -->
                                <button class="delete-button" @click="confirmDelete_collect(v)">取消收藏</button>
                            </div>
                            <h2 class="topic-title" @click="goDetails(v)">{{ v.title }}</h2>
                            <div class="topic-content">{{ v.content }}</div>
                            <div>
                                <p class="publish-time">发布时间:{{ v.publish_time }}</p>
                            </div>
                        </div>
                        <el-row :gutter="20" class="action-area">
                            <el-col :span="4">
                                <el-button type="text" @click="voteUp(v)">
                                    <i class="iconfont icon-xiangshang1"></i> 赞成 {{ v.likes_number }}
                                </el-button>
                            </el-col>
                            <el-col :span="4">
                                <el-button type="text" @click="voteDown(v)">
                                    <i class="iconfont icon-xiangxia2"></i>反对{{ v.dislikes_number }}
                                </el-button>
                            </el-col>
                            <el-col :span="4">
                                <el-button type="text" @click="goDetails(v)">
                                    <i class="iconfont icon-xiaoxi"></i> {{ v.comment_count }}条评论
                                </el-button>
                            </el-col>
                        </el-row>
                    </li>
                </ul>
                <div v-else>
                    <el-empty description="暂无收藏的话题"></el-empty>
                </div>
            </div>
        </el-tab-pane>
        <el-tab-pane label="关注">
            <div class="guanzhu" v-if="concern && concern.length > 0">
                <el-card v-for="(item, index) in concern" :key="index" style="margin:10px">
                    <div class="clearfix">
                        <el-descriptions title='个人信息'>
                            <el-descriptions-item label="姓名：">{{ item.name }}</el-descriptions-item>
                            <el-descriptions-item label="生日：">{{ item.birthday }}</el-descriptions-item>
                            <el-descriptions-item label="电话：">{{ item.tel }}</el-descriptions-item>
                            <el-descriptions-item label="账号：">{{ item.username }}</el-descriptions-item>
                            <br>
                            <el-descriptions-item label="年龄：">
                                <el-tag size="small"> {{ item.age }}</el-tag>
                            </el-descriptions-item>
                            <el-descriptions-item label="邮箱：">{{ item.email }}</el-descriptions-item>
                            <el-descriptions-item label="居住地址：">{{ item.address }}</el-descriptions-item>
                        </el-descriptions>
                       
                    </div>
                    <div> <button class="delete-button2" @click="canclelike(item)">取消关注</button></div>
                </el-card>
            </div>
            <div v-else>
                <el-empty description="暂无关注"></el-empty>
            </div>
        </el-tab-pane>
        <el-tab-pane label="我发布的话题">
            <div class="Topstory-content">
                <ul v-if="usertopics && usertopics.length > 0">
                    <li v-for="v in usertopics" :key="v.id" class="topic-item">
                        <div>
                            <div class="topstory-hd">
                                <span>{{ v.publisher_name }}</span>
                                <!-- 添加删除按钮 -->
                                <button class="delete-button" @click="confirmDelete_usertopic(v)">删除话题</button>
                            </div>
                            <h2 class="topic-title" @click="goDetails(v)">{{ v.title }}</h2>
                            <div class="topic-content">{{ v.content }}</div>
                            <div>
                                <p class="publish-time">发布时间:{{ v.publish_time }}</p>
                            </div>
                        </div>
                        <el-row :gutter="20" class="action-area">
                            <el-col :span="4">
                                <el-button type="text" @click="voteUp(v)">
                                    <i class="iconfont icon-xiangshang1"></i> 赞成 {{ v.likes_number }}
                                </el-button>
                            </el-col>
                            <el-col :span="4">
                                <el-button type="text" @click="voteDown(v)">
                                    <i class="iconfont icon-xiangxia2"></i>反对{{ v.dislikes_number }}
                                </el-button>
                            </el-col>
                            <el-col :span="4">
                                <el-button type="text" @click="goDetails(v)">
                                    <i class="iconfont icon-xiaoxi"></i> {{ v.comment_count }}条评论
                                </el-button>
                            </el-col>
                        </el-row>
                    </li>
                </ul>
                <div v-else>
                    <el-empty description="暂无发表话题"></el-empty>
                </div>
            </div>
        </el-tab-pane>

    </el-tabs>
    <router-view />
</template>


<script setup>
import { ref, onMounted, reactive } from 'vue'
import axios from 'axios'
import avatar1 from'@/assets/image/useravatar/avatar1.jpg'
import avatar2 from'@/assets/image/useravatar/avatar2.jpg'
import avatar3 from'@/assets/image/useravatar/avatar3.jpg'
import { useRouter } from 'vue-router'
const errorHandler = () => true
const token = localStorage.getItem('token')
const collect = ref([])  //用户收藏话题
const concern = ref([])   //用户关注的人
const usertopics = ref([])   //用户发表的话题
const router = useRouter();
const tabPosition = ref('left')
const user = ref([])
const dialogTableVisible = ref(false)
const ruleForm = reactive({
    webname: '',
    tel: '',
    birthday: '',
    email: '',
    address: '',
    name: '',

})
let image;
const number =  ref(Math.floor(Math.random() * 3) + 1);
switch (number.value) {
  case 1:
    image = avatar1;
    break;
  case 2:
    image = avatar2;
    break;
  case 3:
    image = avatar3;
    break;
  default:
    // 默认头像或者处理逻辑
    break;
}
const formatDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

const submitForm = async () => {
    const formattedDate = formatDate(new Date(ruleForm.birthday));
    try {
        const response = await axios.post('http://127.0.0.1:8000/user/api/submitForm/', {
            token: token,
            usermsg: ruleForm,
            birthday: formattedDate
        }, {
            headers: {
                'Content-Type': 'application/json'
            }
        });
        alert(response.data.message)
    } catch (error) {
        console.error('Error fetching data', error)
    }
    dialogTableVisible.value = false
    window.location.reload(); // 重新加载页面
}

function goDetails(c) {
    router.push({
        name: 'topicdetails',
        params: {
            id: c.id
        }
    });
}

const fetchData = async () => {
    try {
        const response = await axios.post('http://127.0.0.1:8000/user/api/usermsg/', {
            token: token,
        }, {
            headers: {
                'Content-Type': 'application/json'
            }
        });
        console.log(response.data)
        user.value = response.data.user
        collect.value = response.data.collected_topics
        concern.value = response.data.concerned_users
        usertopics.value = response.data.usertopics
    } catch (error) {
        console.error('Error fetching data', error)
    }
}
onMounted(async () => {
    fetchData();
});
function confirmDelete_usertopic(topic) {
    if (window.confirm(`确定要删除话题 "${topic.title}" 吗？`)) {
        // 用户点击确定，执行删除操作
        deleteTopic_usertopic(topic.id);
    } else {
        // 用户点击取消，不执行任何操作
    }
}

function canclelike(topic) {
    if (window.confirm(`确定取消关注用户： "${topic.title}" 吗？`)) {
        // 用户点击确定，执行删除操作
        deleteUser_canclelike(topic.id);
    } else {
        // 用户点击取消，不执行任何操作
    }
}
async function deleteUser_canclelike(id) {
    try {
        const response = await axios.post(`http://127.0.0.1:8000/user/api/canclelike/`,{
            id:id,
            token:token
        });
        if (response.status === 200) {
            // 删除成功，刷新页面或者更新前端数据
            alert(response.data.message);
            window.location.reload(); // 重新加载页面
        } else {
            // 删除失败
            alert('删除失败');
        }
    } catch (error) {
        // 请求失败
        console.error('删除请求失败', error);
        alert('删除请求失败');
    }

}
function confirmDelete_collect(topic) {
    if (window.confirm(`确定要删除收藏话题 "${topic.title}" 吗？`)) {
        // 用户点击确定，执行删除操作
        deleteTopic_collectc(topic.id);
    } else {
        // 用户点击取消，不执行任何操作
    }
}
async function deleteTopic_usertopic(id) {
    try {
        const response = await axios.delete(`http://127.0.0.1:8000/user/api/delete_usertopic/${id}/`);
        if (response.status === 200) {
            // 删除成功，刷新页面或者更新前端数据
            alert('删除成功');
            window.location.reload(); // 重新加载页面
        } else {
            // 删除失败
            alert('删除失败');
        }
    } catch (error) {
        // 请求失败
        console.error('删除请求失败', error);
        alert('删除请求失败');
    }

}

async function deleteTopic_collectc(id) {
    try {
        const response = await axios.post(`http://127.0.0.1:8000/user/api/delete_usercollect/`, {
            token: token,
            id:id
        }, {
            headers: {
                'Content-Type': 'application/json'
            }
        });
        if (response.status === 200) {
            // 删除成功，刷新页面或者更新前端数据
            alert('删除成功');
            window.location.reload(); // 重新加载页面
        } else {
            // 删除失败
            alert('删除失败');
        }
    } catch (error) {
        // 请求失败
        console.error('删除请求失败', error);
        alert('删除请求失败');
    }
}

// 定义赞成按钮的点击事件处理函数
async function voteUp(v) {
    try {
        // 向后端发送请求，表示对指定话题进行点赞
        const response = await axios.post(`http://127.0.0.1:8000/user/api/vote_up/${v.id}/`);
        // 根据后端返回的数据更新前端页面
        const updatedTopic = response.data; // 假设后端返回更新后的话题对象
        const index = usertopics.value.findIndex(topic => topic.id === v.id);
        if (index !== -1) {
            usertopics.value[index] = updatedTopic; // 更新话题列表中的对应项
        }
        window.location.reload(); // 重新加载页面

    } catch (error) {
        console.error('赞成失败', error);
        // 处理请求失败的情况
    }
}

// 定义取消赞成按钮的点击事件处理函数
async function voteDown(v) {
    try {
        // 向后端发送请求，表示对指定话题进行点赞
        const response = await axios.post(`http://127.0.0.1:8000/user/api/vote_down/${v.id}/`);
        // 根据后端返回的数据更新前端页面
        const updatedTopic = response.data; // 假设后端返回更新后的话题对象
        const index = usertopics.value.findIndex(topic => topic.id === v.id);
        if (index !== -1) {
            usertopics.value[index] = updatedTopic; // 更新话题列表中的对应项
        }
        window.location.reload(); // 重新加载页面

    } catch (error) {
        console.error('赞成失败', error);
        // 处理请求失败的情况
    }
}



</script>


<style>
/* 话题列表项 */
.topic-item {
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 10px;
    margin-bottom: 10px;
}

/* 话题标题 */
.topic-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 5px;
}

/* 话题内容 */
.topic-content {
    font-size: 14px;
    color: #666;
    margin-bottom: 10px;
}

/* 发布时间 */
.publish-time {
    font-size: 12px;
    color: #999;
}

/* 动作区 */
.action-area {
    align-items: center;
}

.webname {
    margin-bottom: 0;
}

.demo-tabs>.el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
}

.el-tabs--right .el-tabs__content,
.el-tabs--left .el-tabs__content {
    height: 100%;
}

/* 关注 */
.Topstory-content {
    display: flex;
    flex-wrap: wrap;
}

.Topstory-content ul {
    width: 100%;
    padding: 20px
}

.Topstory-content>ul>li {
    border-bottom: 1px solid #eee;
    padding: 10px 0;
}

.topic-item {
    position: relative;
    padding-right: 40px;
    /* 为删除按钮留出空间 */
}

.delete-button {
    position: absolute;
    top: 0;
    right: 0;
    background-color: transparent;
    border: none;
    color: red;
    cursor: pointer;
    font-size: 14px;
}

.delete-button2 {
    top: 0;
    right: 0;
    background-color: transparent;
    border: none;
    color: red;
    cursor: pointer;
    font-size: 14px;
}
.delete-button:hover {
    color: darkred;
    text-decoration: underline;
}


</style>